package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(urlPatterns = { "/*" }, initParams = { @WebInitParam(name = "encoding", value = "UTF-8") })
public class EncodingFilter implements Filter {
	protected String encoding = null;
	protected FilterConfig filterConfig = null;

	public EncodingFilter() {
		// TODO Auto-generated constructor stub
	}

	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("字符集过滤器销毁!");
		this.encoding = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String encoding = this.encoding;
		if (encoding != null) {
			// 设置request的编码格式
			request.setCharacterEncoding(encoding);
			// 设置response字符编码
			response.setContentType("text/html; charset=" + encoding);
		} else {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=UTF-8");
		}
		chain.doFilter(request, response);// 传递过滤链
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("字符集过滤器初始化!");
		this.filterConfig = fConfig;
		this.encoding = filterConfig.getInitParameter("encoding");// 获取传递过来的初使化编码
	}

}
